// FileList.cpp: implementation of the CImageFileList class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "FileList.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

ImageFileList::ImageFileList(const string& dir) : baseDir(dir)
{
	GetFiles(baseDir.c_str(), "*.*");
}

ImageFileList::~ImageFileList()
{

}

bool ImageFileList::getFile(int position, string& file)
{
	if (position > files.size())
		return false;

	file = files[position];

	return true;
}

int ImageFileList::listSize(void)
{
	return files.size();
}

void ImageFileList::GetFiles(const char *dirName, char *fileMask)
{
	char *fileName;
	char curDir[256];
	char fullName[256];
	HANDLE fileHandle;
	WIN32_FIND_DATA findData;

	// saves current dir so it can restore it
	if (!GetCurrentDirectory(256, curDir))
		return;

	// if the directory name is neither . or .. then change to it
	if (strcmp(dirName, ".") && strcmp(dirName, ".."))
	{
		if (!SetCurrentDirectory(dirName))
			return;
	}
	else
		return;

	// print out the current directory name
	if (!GetFullPathName(fileMask, 256, fullName, &fileName))
		return;

	//cout << endl << "Directory - " << fullName << endl;

	// Loop through all the files in the directory
	fileHandle = FindFirstFile(fileMask, &findData);
	while (fileHandle != INVALID_HANDLE_VALUE)
	{
		// if the name is a directory, recursively walk it. Otherwise print the file data
		if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			GetFiles(findData.cFileName, fileMask);
		}
		else
		{
			string testFile(findData.cFileName);
			
			if (testFile.rfind(".jpg") != string::npos)
			{
				string foundFile;

				foundFile += dirName;
				foundFile += "/";
				foundFile += findData.cFileName;

				// Now switch the slashes around
				for(int i = 0, tfind; (tfind = foundFile.find("\\", i)) != string::npos; i = tfind + 1)
				{
					foundFile[tfind] = '/';
				}				

				files.push_back(foundFile);			
			}
		}

		// loop through the remaining entries
		if (!FindNextFile(fileHandle, &findData))
			break;
	}

	// clean up and restore the directory
	FindClose(fileHandle);
	SetCurrentDirectory(curDir);
}
